package com.fhs.tools.ribbon.rule;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.Server;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class NacosDebuggerRule extends AbstractLoadBalancerRule {

    @Autowired
    private NacosDiscoveryProperties nacosDiscoveryProperties;

    /**
     * 重写choose方法
     *
     * @param key
     * @return
     */
    @SneakyThrows
    @Override
    public Server choose(Object key) {
        //获取服务配置的集群名
        String clusterName = nacosDiscoveryProperties.getClusterName();
        //当前的版本号 配置文件配置的metadata信息
        String currentVersion = nacosDiscoveryProperties.getMetadata().get("version");
        //获取负载均衡器
        BaseLoadBalancer baseLoadBalancer = (BaseLoadBalancer) getLoadBalancer();
        //调用服务的名字
        String invokedServerName = baseLoadBalancer.getName();
        //获取namingServer（包含nacos注册发现相关api）
        NamingService namingService = nacosDiscoveryProperties.namingServiceInstance();
        //获取被调用的服务的所有实例
        List<Instance> invokedAllInstanceList = namingService.getAllInstances(invokedServerName);
        if(invokedAllInstanceList.isEmpty()){
            throw new RuntimeException(invokedServerName + "找不到服务，请检查服务提供者是否已经启动并且已经注册到nacos中");
        }
        Instance invokedInstance = null;
        String localIp = this.getLocalhostIp();
        //192.168.0  获取到同网段ip
        String localIpStart = localIp.substring(0, localIp.lastIndexOf("."));
        for (Instance instance : invokedAllInstanceList) {
            if (instance.getIp().equals(localIp)) {
                return new NacosServer(instance);
            } else if (instance.getIp().startsWith(localIpStart)) {
                invokedInstance = instance;
            }
        }
        return new NacosServer(invokedInstance != null ? invokedInstance : invokedAllInstanceList.get(0));
    }

    @Override
    public void initWithNiwsConfig(IClientConfig iClientConfig) {

    }

    /**
     * 获取本地ip
     *
     * @return 本机ip
     */
    public String getLocalhostIp() {
        try {
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress ip = (InetAddress) addresses.nextElement();
                    if (ip != null
                            && ip instanceof Inet4Address
                            && !ip.isLoopbackAddress() //loopback地址即本机地址，IPv4的loopback范围是127.0.0.0 ~ 127.255.255.255
                            && ip.getHostAddress().indexOf(":") == -1) {
                        return ip.getHostAddress();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
